/*
 * @Description:
 * @Date: 2024-02-25 20:49:38
 * @LastEditTime: 2024-03-03 18:12:31
 * @FilePath: /pure-admin-thin/src/store/modules/user.ts
 */
import { defineStore } from "pinia";
import { store } from "@/store";
import { userType } from "./types";
import { storageSession } from "@pureadmin/utils";
import {
  ProductResult,
  getProduct,
  addProduct,
  updateProduct,
  getProductList,
  ProductListResult,
  delProduct
} from "@/api/product";
import { type DataInfo, sessionKey } from "@/utils/auth";

export const useProductStore = defineStore({
  id: "pure-product",
  state: (): userType => ({
    // 用户名
    username: storageSession().getItem<DataInfo>(sessionKey)?.username ?? "",
    // 页面级别权限
    roles: storageSession().getItem<DataInfo>(sessionKey)?.roles ?? []
  }),
  actions: {
    /** 存储用户名 */
    SET_USERNAME(username: string) {
      this.username = username;
    },
    /** 存储角色 */
    SET_ROLES(roles: Array<string>) {
      this.roles = roles;
    },
    /** 获取商品详情*/
    async getProductInfo(id: string) {
      return new Promise<ProductResult>((resolve, reject) => {
        getProduct(id)
          .then(data => {
            if (data) {
              resolve(data);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    async getProductList() {
      return new Promise<ProductListResult>((resolve, reject) => {
        getProductList()
          .then(data => {
            if (data) {
              resolve(data);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    async addProductInfo(_data: any) {
      return new Promise<ProductResult>((resolve, reject) => {
        addProduct(_data)
          .then(data => {
            if (data) {
              resolve(data);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    async updateProductInfo(id: string, _data: any) {
      return new Promise<ProductResult>((resolve, reject) => {
        updateProduct(id, _data)
          .then(data => {
            if (data) {
              resolve(data);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    async delProductInfo(id: string) {
      return new Promise<ProductResult>((resolve, reject) => {
        delProduct(id)
          .then(data => {
            if (data) {
              resolve(data);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  }
});

export function useProductStoreHook() {
  return useProductStore(store);
}
